<template>
  <div :class="{'show': show}" class="header-search">
    <SvgIcon name="search" size="20" @click.stop="click" />
    <el-select
      ref="headerSearchSelect"
      class="header-search-select"
      v-model="search"
      filterable
      remote
      :remote-method="querySearch"
      placeholder="Search"
      @change="change"
    >
      <el-option v-for="item in options" :key="item.path" :value="item">
        {{ item.title.map(item => t('route.' + item)).join(' > ') }}
      </el-option>
    </el-select>
  </div>
</template>

<script lang="ts" setup>
import Fuse from 'fuse.js'
import SvgIcon from '@/components/SvgIcon/index.vue'
import { ref, nextTick, onMounted, computed, watch, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { TagView } from '@/store/modules/tagsView/state';
import { RouteRecordRaws } from '@/router';
import path from 'path-browserify';
import { useI18n } from "vue-i18n";

const { t } = useI18n()

type SelectOptions = {
  path: String
  title: string[]
}

const $router = useRouter()

const show = ref(false)
const headerSearchSelect = ref(null)
let options = ref<SelectOptions[]>([])
let fuse = reactive({})

// 过滤路由
const generateRoutes = (routes: RouteRecordRaws[], basePath = '/', prefixTitle = []) => {
  let res: any[] = []
  for (const router of routes) {
    if (router.hidden) { continue }
    const data = {
      path: path.resolve(basePath, router.path),
      title: [...prefixTitle] as unknown[]
    }

    if (router.meta && router.meta.title) {
      data.title = [...data.title, router.meta.title]
      if (router.redirect !== 'noRedirect') {
        res.push(data)
      }
    }

    if (router.children) {
      const tempRoutes = generateRoutes(router.children, data.path, data.title as never[])
      if (tempRoutes.length >= 1) {
        res = [...res, ...tempRoutes]
      }
    }
  }
  return res as any[]
}

// 获取可以搜索的列表
const routes = computed(() =>  $router.options.routes)

// Fuse配置属性
const opt = {
  shouldSort: true,
  threshold: 0.4,
  location: 0,
  distance: 100,
  maxPatternLength: 32,
  minMatchCharLength: 1,
  keys: [{
    name: 'title',
    weight: 0.7
  }, {
    name: 'path',
    weight: 0.3
  }]
}
const search = ref('')

let searchPool = ref<SelectOptions[]>([])
watch(() => routes.value, (val) => {
  searchPool.value = generateRoutes(routes.value)
})
watch(() => searchPool.value, (val) => {
  initFuse(val)
})
onMounted(() => {
  searchPool.value = generateRoutes(routes.value)
})
// 初始化fuse模糊搜索
const initFuse = (_list:SelectOptions[] = []) => {
  fuse = new Fuse(_list, opt)
}

const querySearch = (query: string) => {
  if (query !== '') {
    const data = (fuse as any).search(query)
    options.value = data.map((e: { item: any; }) => e.item)
  } else {
    options.value = []
  }
}

watch(
  () => show.value,
  (val) => {
    if (val) {
      document.body.addEventListener('click', close)
    } else {
      document.body.removeEventListener('click', close)
    }
  }
)

const click = () => {
  show.value = !show.value
  if (show.value) {
    headerSearchSelect.value && (headerSearchSelect.value as any).focus()
  }
}

const close = () => {
  headerSearchSelect.value && (headerSearchSelect.value as any).blur()
  options.value = []
  show.value = false
}

const change = (val: TagView) => {
  $router.push(val.path)
  search.value = ''
  options.value = []
  nextTick(() => {
    show.value = false
  })
}

</script>

<style lang="scss" scoped>
.header-search {
  font-size: 0 !important;
  padding-top: 8px !important;
  cursor: pointer;
  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;
    margin-top: -15px !important;
    
    :deep(.el-input__inner)  {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
      height: 30px !important;
    }
  }
  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>